package org.example.controller;

import org.example.service.DeviceService;
import org.example.service.SceneService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 首页控制器
 */
@RestController
@RequestMapping("/home")
@CrossOrigin(origins = "*")
public class HomeController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private DeviceService deviceService;
    
    @Autowired
    private SceneService sceneService;
    
    /**
     * 获取用户首页数据
     */
    @GetMapping("/dashboard/{userId}")
    public ResponseEntity<?> getDashboard(@PathVariable Long userId) {
        try {
            Map<String, Object> dashboard = new HashMap<>();
            
            // 用户统计
            long totalUsers = userService.countActiveUsers();
            long totalDevices = deviceService.countDevicesByUserId(userId);
            long onlineDevices = deviceService.countOnlineDevicesByUserId(userId);
            long totalScenes = sceneService.countScenesByUserId(userId);
            long activeScenes = sceneService.countActiveScenesByUserId(userId);
            
            dashboard.put("userStats", Map.of(
                "totalUsers", totalUsers
            ));
            
            dashboard.put("deviceStats", Map.of(
                "totalDevices", totalDevices,
                "onlineDevices", onlineDevices,
                "offlineDevices", totalDevices - onlineDevices
            ));
            
            dashboard.put("sceneStats", Map.of(
                "totalScenes", totalScenes,
                "activeScenes", activeScenes,
                "inactiveScenes", totalScenes - activeScenes
            ));
            
            return ResponseEntity.ok(dashboard);
            
        } catch (Exception e) {
            return ResponseEntity.status(500).body("获取首页数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取系统状态
     */
    @GetMapping("/system-status")
    public ResponseEntity<?> getSystemStatus() {
        try {
            Map<String, Object> status = new HashMap<>();
            status.put("status", "running");
            status.put("message", "系统运行正常");
            status.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(status);
            
        } catch (Exception e) {
            return ResponseEntity.status(500).body("获取系统状态失败：" + e.getMessage());
        }
    }
}
